#include "client_vista_MainHandler.h"
#include <gtkmm/main.h>
#include <log4cpp/Category.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/SimpleLayout.hh>
#include <log4cpp/TimeStamp.hh>
#include <signal.h>
#define LOGFILE "./Cliente.log"
#define END_APP 0
#define ACTIVE_APP 1
log4cpp::Appender *appender = new log4cpp::FileAppender("FileAppender",
		LOGFILE);
log4cpp::Layout *layout = new log4cpp::SimpleLayout();
log4cpp::Category& category = log4cpp::Category::getInstance("Category");



int main(int argc, char *argv[]) {
	appender->setLayout(layout);
	category.setAppender(appender);
	category.setPriority(log4cpp::Priority::INFO);
	signal(SIGPIPE, SIG_IGN);

	//Obtengo fecha y hora
	time_t rawtime;
	time(&rawtime);
	struct tm * timeinfo = localtime(&rawtime);
	time_t tim = time(NULL);
	tm *now = localtime(&tim);
	category.info("Client log started at %02d:%02d of %02d/%02d/%d",
			now->tm_hour, now->tm_min, now->tm_mday, now->tm_mon + 1,
			now->tm_year + 1900);

	Cliente *client = new Cliente();
	std::string properties("./cfg.properties");
	std::ifstream cfg(properties.c_str(), std::ifstream::in);
	std::ifstream login("./login", std::ifstream::in);

	Socket *sock = new Socket();

	bool connect = false;
	Gtk::Main kit(argc, argv);
	if (cfg.is_open() and login.is_open()) {
		cfg.close();
		login.close();

		ClientCfg cfg(properties);
		cfg.Initialize();
		//Cargo variables desde archivo de configuracion
		std::string storage_path = cfg.getStorage_path();
		std::string indice_path = cfg.getIndice_path();
		std::string ip_server = cfg.getIp_server();
		std::string login_path = cfg.getLogin_path();
		std::string user, pass;

		bool login_error = true;
		bool not_max_tries = true;
		Index indice(&login_path);
		indice.LoadFromDisk();
		std::string field_user = "USER";
		std::string field_pass = "PASS";
		user = indice.GetSecond(&field_user);
		pass = indice.GetSecond(&field_pass);

		try {
			sock->Connect(&ip_server, cfg.getPort());
			client->setSocket(sock);
			client->register_to_server(user, pass); //Agregar el cliente
			std::string received = sock->RecvNextMsg();
			Decoder d;
			Message *msg = d.parser(received);
			client->process_logging(d.get_id_msg(), &login_error,
					&not_max_tries);
			delete msg;
			if (not login_error) {
				//se conecto
				category.notice("Connection established!");
				client->setUserPass(user, pass);
				client->initialize(sock, storage_path, indice_path, login_path,
						cfg.getPolling(), user, pass);
				client->start();
				category.info("Information connection:");
				category.info("Ip server: "+ip_server);
				category.info("Port: %d", cfg.getPort());
				category.info("Storage: " + storage_path);
				category.info("Polling interval: %d sec", cfg.getPolling());
				MainHandler connected(sock, "Unregister", ACTIVE_APP, client);
				Gtk::Main::run(connected);
				MainHandler end_app(sock, "End", END_APP, client);
				Gtk::Main::run(end_app);
				connect = true;
			}
		} catch (const CommunicationException& e) {
			connect = false;

		}
	}
	if (not connect) {

		MainHandler window(sock, "Connect", ACTIVE_APP, client);
		Gtk::Main::run(window);
		if (not window.is_end_program()) {
			try {
				MainHandler connected(sock, "Unregister", ACTIVE_APP, client);
				Gtk::Main::run(connected);
				MainHandler end_app(sock, "End", END_APP, client);
				Gtk::Main::run(end_app);
			} catch (const CommunicationException& e) {
			}

		}
	}

	return 0;
}
